#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMenuBar>
#include <QPlainTextEdit>
#include <QFileDialog>
#include <QLabel>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /////////////通过窗口来读写文件，并利用QFileInfo来获取信息/////////////
    /// \brief menubar
    ///
    QMenuBar* menubar = this->menuBar();
    QMenu* menu = new QMenu("文件");
    menubar->addMenu(menu);
    QAction* action = new QAction("打开");
    QAction* action_1 = new QAction("保存");
    menu->addAction(action_1);
    menu->addAction(action);

    QPlainTextEdit* edit = new QPlainTextEdit();
    QFont font;
    font.setPixelSize(25);
    edit->setFont(font);
    this->setCentralWidget(edit);

    QStatusBar* bar = this->statusBar();

    connect(action, &QAction::triggered, this, [this, bar](){
        QString filename = QFileDialog::getOpenFileName();
        bar->showMessage(filename + ": open successfully");
        QFile file(filename);
        bool ret = file.open(QIODevice::ReadOnly);
        if(!ret)
            {
            bar->showMessage(filename + ": open error!");
            return;
        }
        QString text = file.readAll();;
        QPlainTextEdit* edit = new QPlainTextEdit();
        this->setCentralWidget(edit);
        edit->setPlainText(text);

        QFileInfo info(filename);
        qDebug() << info.fileName();
        qDebug() << info.suffix();
        qDebug() << info.size();
        qDebug() << info.path();
    });

    connect(action_1, &QAction::triggered, this, [this, bar, edit](){
        //先弹出打开文件对话框
        QString filename = QFileDialog::getSaveFileName();
        QFile file(filename);
        bool ret = file.open(QIODevice::WriteOnly);
        if(!ret)
        {
            bar->showMessage(filename + ": save fail");
            return;
        }

        //在状态栏中显示
        bar->showMessage(filename + "open success");
        //写文件
        QString text = edit->toPlainText();
        file.write(text.toUtf8());
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}
